import tkinter as tk
import threading
import time
import math
import random
import sys
from pathlib import Path
import pygame

# 路径设置
if hasattr(sys, '_MEIPASS'):
    root_path = Path(sys._MEIPASS)
else:
    root_path = Path(__file__).parent

class MusicThread(threading.Thread):
    """音乐播放线程"""
    
    def __init__(self, file_path):
        super().__init__()
        self.file_path = file_path
        self.is_playing = False
        self._stop_requested = False
        self.daemon = True
    
    def run(self):
        """线程主函数"""
        try:
            if not pygame.mixer.get_init():
                pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=1024)
            
            pygame.mixer.music.load(str(self.file_path))
            pygame.mixer.music.play()
            self.is_playing = True
            
            while self.is_playing and not self._stop_requested:
                if not pygame.mixer.music.get_busy():
                    self.is_playing = False
                else:
                    time.sleep(0.1)
                    
        except Exception as e:
            print(f"播放错误: {str(e)}")
        finally:
            if pygame.mixer.get_init():
                pygame.mixer.music.stop()
                pygame.mixer.quit()
    
    def stop_playback(self):
        """停止播放"""
        self._stop_requested = True
        self.is_playing = False

class ShowCare:
    def __init__(self):
        self.root = tk.Tk()
        self.root.withdraw()
        
        music_path = root_path / "background_music.MP3"
        print(f"音乐路径: {music_path}")
        self.music_thread = MusicThread(music_path)
        self.music_thread.start()

        # self.init_create_msg()
        self.root.after(200, self.init_create_msg)

        self.root.mainloop()       


    def init_create_msg(self):
        """初始化弹窗参数"""
        self.dialog_num = 150  # 增加弹窗数量以便更好形成心形
        self.msg_list = []
        
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        self.available_grid_positions = self._create_screen_grid(self.dialog_num, screen_width, screen_height)

        self.name = "温馨提醒"
        self.What_I_want_to_say = [
            "降温了，你的外套够暖吗？","看你最近有点疲惫，是有什么烦心事吗？\n我都在",
            "知道你忙，但也要记得按时吃饭呀","累的时候，允许自己当个小孩，歇一歇吧",
            "你喜欢的那个口味，我刚好路过，给你带了一份","小小休息是为了更好的出发\n继续加油吧",
            "身体是革命的本钱\n照顾好自己比啥都重要","雨天慢行，带伞了吗？\n别让雨水淋湿了你的心情",
            "把疲惫留给昨天吧，轻松迎接夜晚的宁静","心里事儿太多就说出来嘛\n我一直在这里倾听你的心声",
            "寒冷冬日，有你真暖和，感谢一路陪伴和支持","平凡的日子也要闪闪发光\n每一天都值得被认真对待",
            "虽然距离遥远但心意相通\n想你的时候空气都是甜的","这些天辛苦了","有没有要帮忙的？",
            "别怕，慢慢来\n我就在旁边","你已经做得很好了\n别太苛责自己",
            "这件事确实不容易，换成是我也会觉得难","无论结果如何\n你都不是一个人面对",
            "我们一起想想办法？\n或许能换个角度看看","这次没达到预期\n但你积累的经验特别宝贵",
            "压力大的时候\n记得你背后还有我们","照顾别人的时候\n也别忘了心疼自己",
            "只要今天比昨天强就好！","别怕，你肯定能行！","只要努力，下次就一定能考好",
            "尽管很难，但你一直没有放弃","你做事情的态度非常不错！",
            "你一点都不怕困难，太难得了！","没关系，一切都会好起来的！"
        ]

        self.color = [
            "#FFB6C1","#FFFFC3","#87CEFA","#AFEEEE", 
            "#FFC0CB","#ADD8E6","#CBFFFF","#FFDAB9", 
            "#FFA07A","#C9C9FF","#FF8295","#FE9DAB"  
        ]
        
        self.dialog_process(self.dialog_num)

    def _create_screen_grid(self, grid_count, screen_width, screen_height):
        """将屏幕平均分成指定数量的网格"""
        grid_cols = int(grid_count ** 0.5)
        grid_rows = (grid_count + grid_cols - 1) // grid_cols
        grid_width = screen_width // grid_cols
        grid_height = screen_height // grid_rows
        
        grid_positions = []
        for row in range(grid_rows):
            for col in range(grid_cols):
                if len(grid_positions) >= grid_count:
                    break
                center_x = col * grid_width + grid_width // 2
                center_y = row * grid_height + grid_height // 2
                grid_positions.append((center_x, center_y))
        return grid_positions

    def create_message_window(self, message, color, x, y):
        """直接创建Tkinter弹窗（优化版）"""
        # 创建顶级窗口
        window = tk.Toplevel(self.root)
        window.title(self.name)
        window.overrideredirect(True)  # 移除标题栏
        window.attributes('-topmost', True)  # 始终置顶
        
        # 设置窗口样式
        window.configure(bg=color, highlightthickness=2, highlightbackground='black')
        
        # 创建标签显示消息
        label = tk.Label(
            window, 
            text=message, 
            bg=color, 
            fg='black', 
            font=('微软雅黑', 12),
            wraplength=250,
            justify='center'
        )
        label.pack(padx=15, pady=15)
        
        # 设置窗口位置和大小
        window.geometry(f"300x100+{int(x)}+{int(y)}")
        window.deiconify()  # 显示窗口
        
        return window

    def dialog_process(self, num):
        """弹窗动作流程（使用Tkinter的after方法优化）"""
        # 创建初始弹窗
        for i in range(num):
            self.create_msg()
            self.root.after(500, self.create_msg)  # 分散创建时间
        
        # 安排后续动作
        self.root.after(1000, self.show_center_message)
        self.root.after(3000, lambda: self.change_color("#FF8295"))
        self.root.after(4000, self.arrange_hearts_shape)
        self.root.after(6000, self.exit_application)

    def create_msg(self):
        """创建单个弹窗"""
        if not self.available_grid_positions:
            return
            
        message = random.choice(self.What_I_want_to_say)
        color = random.choice(self.color)
        center_x, center_y = random.choice(self.available_grid_positions)
        self.available_grid_positions.remove((center_x, center_y))
        
        # 计算窗口位置（居中显示）
        x = max(0, center_x - 150)  # 窗口宽度约300
        y = max(0, center_y - 50)   # 窗口高度约100
        
        # 确保不超出屏幕边界
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = min(x, screen_width - 300)
        y = min(y, screen_height - 100)
        
        # 直接创建弹窗
        window = self.create_message_window(message, color, x, y)
        self.msg_list.append(window)

    def show_center_message(self):
        """显示居中提示消息"""
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = (screen_width - 300) // 2
        y = (screen_height - 100) // 2
        
        center_window = self.create_message_window(
            "没关系，一切都会好起来的！", "#FF8295", x, y
        )
        
        # 3秒后自动关闭居中消息
        self.root.after(3000, center_window.destroy)

    def change_color(self, color):
        """改变所有弹窗颜色"""
        for window in self.msg_list:
            if window.winfo_exists():  # 检查窗口是否还存在
                # 获取窗口中的所有子部件并更新颜色
                for widget in window.winfo_children():
                    if isinstance(widget, tk.Label):
                        widget.configure(bg=color)
                window.configure(bg=color)
        self.root.update()

    def arrange_hearts_shape(self):
        """将弹窗排列成爱心形状（优化版）"""
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        
        # 预计算心形点（性能优化）
        num_points = len(self.msg_list)
        heart_points = []
        for i in range(num_points):
            t = 2 * math.pi * i / max(num_points, 1)
            x_eq = 16 * (math.sin(t) ** 3)
            y_eq = 13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t)
            heart_points.append((x_eq, y_eq))
        
        # 计算缩放比例
        center_x, center_y = screen_width // 2, screen_height // 2
        scale = min(screen_width * 0.3, screen_height * 0.3)
        
        # 使用动画效果排列弹窗
        for i, window in enumerate(self.msg_list):
            if i < len(heart_points) and window.winfo_exists():
                point_x, point_y = heart_points[i]
                x = center_x + point_x * scale - 150
                y = center_y - point_y * scale - 50
                
                # 边界检查
                x = max(0, min(x, screen_width - 300))
                y = max(0, min(y, screen_height - 100))
                
                # 直接移动窗口
                window.geometry(f"300x100+{int(x)}+{int(y)}")
                
                # 更新标签文本为爱心符号
                for widget in window.winfo_children():
                    if isinstance(widget, tk.Label):
                        widget.configure(text="❤", font=('Arial', 20))
        
        self.root.update()

    def exit_application(self):
        """退出应用程序"""
        # 渐隐效果关闭弹窗
        for i, window in enumerate(reversed(self.msg_list)):
            if window.winfo_exists():
                self.root.after(100 * i, window.destroy)
        
        # 延迟退出主程序
        self.root.after(1000, self.final_exit)

    def final_exit(self):
        """最终退出清理"""
        self.music_thread.stop_playback()
        self.root.quit()
        self.root.destroy()


if __name__ == "__main__":
    app = ShowCare()
